package com.okaixz.common.utils;

import cn.hutool.core.bean.BeanUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.io.Serializable;
import java.util.Map;
import java.util.function.Function;
import java.util.regex.Pattern;

/** jwt Util
 * author cdz
 * date  2023/5/16
 */
public class JwtUtil {
    private final Pattern GET_PATTERN = Pattern.compile("^get[A-Z].*");
    private final Pattern IS_PATTERN = Pattern.compile("^is[A-Z].*");
    public interface Fn<T,R> extends Function<T,R>, Serializable {}

    private static final Integer expired = 60;// 分钟

    private static final String key = "981814480%##@#@";

    public static String getToken(Object o){
        Map<String, Object> params = BeanUtil.beanToMap(o);
        String token = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, key)
                .setClaims(params)
//                .setExpiration(DateTime.now().offsetNew(DateField.MINUTE, expired))//设置过期时间
                .compact();
        return token;
    }

    /**
     * 获取参数bean
     * @param token
     * @param <T>clazz
     * @return
     */
    public static <T>T parseToken(String token,Class<T> clazz){
        Claims body = null;
        try {
            body = Jwts.parser()
                    .setSigningKey(key)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            e.printStackTrace();
            //过期会报错
            return null;
        }
//        System.out.println("解析结果："+body.toString());
        return BeanUtil.toBean(body, clazz);
    }



}
